@extends('layouts.app')

@section('content')
<div class="container">
    <!-- 添加返回首页按钮 -->
    <div class="row mb-4">
        <div class="col-md-12">
            <a href="{{ route('home') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> 返回首页
            </a>
        </div>
    </div>

    <div class="row justify-content-center">
        <div class="col-md-12">
            <!-- 微信用户统计卡片 -->
            <div class="card mb-4">
                <div class="card-header">
                    微信用户统计
                </div>
                <div class="card-body">
                    <h5 class="card-title">总用户数：{{ $totalUsers }}</h5>
                    @if(request('keyword'))
                        <p class="card-text">当前搜索"{{ request('keyword') }}"的结果数：{{ $searchCount }}</p>
                    @endif
                </div>
            </div>

            <!-- 搜索表单 -->
            <div class="card mb-4">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <form action="{{ route('admin.lottery.index') }}" method="GET" class="row g-3 me-2" style="flex: 1;">
                            <div class="col-md-8">
                                <input type="text" 
                                       class="form-control" 
                                       name="keyword" 
                                       placeholder="输入昵称搜索..." 
                                       value="{{ request('keyword') }}">
                            </div>
                            <div class="col-md-4">
                                <button type="submit" class="btn btn-primary me-2">搜索</button>
                                @if(request('keyword'))
                                    <a href="{{ route('admin.lottery.index') }}" class="btn btn-secondary">清除搜索</a>
                                @endif
                            </div>
                        </form>
                        
                        <div class="d-flex gap-2">
                            <!-- 添加中奖清单链接 -->
                            <a href="{{ route('admin.lottery.winners-list') }}" class="btn btn-info me-2">
                                <i class="fas fa-list"></i> 中奖清单
                            </a>
                            
                            <!-- 摇奖按钮 -->
                            <button type="button" 
                                    class="btn btn-success" 
                                    id="startLotteryBtn">
                                <i class="fas fa-gift"></i> 开始摇奖
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 添加中奖结果显示区域 -->
            <div class="card mb-4" id="winnerCard" style="display: none;">
                <div class="card-header bg-success text-white">
                    <i class="fas fa-trophy"></i> 中奖结果
                </div>
                <div class="card-body text-center">
                    <h3 class="card-title mb-4">恭喜以下用户中奖！</h3>
                    <div class="winner-info">
                        <p class="h4 mb-3">中奖用户ID：<span id="winnerId"></span></p>
                        <p class="h4 mb-3">用户昵称：<span id="winnerNickname"></span></p>
                        <p class="h4 mb-3">OpenID：<span id="winnerOpenid"></span></p>
                        <p class="h4 mb-3">注册时间：<span id="winnerCreatedAt"></span></p>
                    </div>
                    <!-- 添加保存按钮 -->
                    <div class="mt-4">
                        <button type="button" 
                                class="btn btn-primary btn-lg" 
                                onclick="saveResult()"
                                id="saveButton">
                            <i class="fas fa-save"></i> 保存结果
                        </button>
                    </div>
                </div>
            </div>

            <!-- 微信用户列表卡片 -->
            <div class="card mb-4">
                <div class="card-header">微信用户列表</div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>OpenID</th>
                                    <th>昵称</th>
                                    <th>注册时间</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse ($wechatUsers as $user)
                                <tr>
                                    <td>{{ $user->id }}</td>
                                    <td>{{ $user->openid }}</td>
                                    <td>{{ $user->nickname ?? '未设置昵称' }}</td>
                                    <td>{{ $user->created_at }}</td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="4" class="text-center">
                                        @if(request('keyword'))
                                            没有找到匹配"{{ request('keyword') }}"的用户
                                        @else
                                            暂无用户数据
                                        @endif
                                    </td>
                                </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- 分页导航 -->
                    @if ($wechatUsers->hasPages())
                    <nav aria-label="微信用户列表分页">
                        <ul class="pagination justify-content-center">
                            {{-- 页链接 --}}
                            @if (!$wechatUsers->onFirstPage())
                                <li class="page-item">
                                    <a class="page-link" href="{{ $wechatUsers->url(1) }}" aria-label="首页">
                                        <span aria-hidden="true">&laquo;</span>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="{{ $wechatUsers->previousPageUrl() }}">上一页</a>
                                </li>
                            @endif

                            {{-- 页码链接 --}}
                            @php
                                $currentPage = $wechatUsers->currentPage();
                                $lastPage = $wechatUsers->lastPage();
                                $window = 2;
                            @endphp

                            {{-- 显示开始的页码 --}}
                            @if($currentPage > ($window + 1))
                                <li class="page-item"><a class="page-link" href="{{ $wechatUsers->url(1) }}">1</a></li>
                                @if($currentPage > ($window + 2))
                                    <li class="page-item disabled"><span class="page-link">...</span></li>
                                @endif
                            @endif

                            {{-- 显示当前页附近的页码 --}}
                            @for($i = max(1, $currentPage - $window); $i <= min($lastPage, $currentPage + $window); $i++)
                                @if($i == $currentPage)
                                    <li class="page-item active">
                                        <span class="page-link">{{ $i }}</span>
                                    </li>
                                @else
                                    <li class="page-item">
                                        <a class="page-link" href="{{ $wechatUsers->url($i) }}">{{ $i }}</a>
                                    </li>
                                @endif
                            @endfor

                            {{-- 显示结束的页码 --}}
                            @if($currentPage < ($lastPage - $window))
                                @if($currentPage < ($lastPage - $window - 1))
                                    <li class="page-item disabled"><span class="page-link">...</span></li>
                                @endif
                                <li class="page-item">
                                    <a class="page-link" href="{{ $wechatUsers->url($lastPage) }}">{{ $lastPage }}</a>
                                </li>
                            @endif

                            {{-- 下一页和末页链接 --}}
                            @if ($wechatUsers->hasMorePages())
                                <li class="page-item">
                                    <a class="page-link" href="{{ $wechatUsers->nextPageUrl() }}">下一页</a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="{{ $wechatUsers->url($lastPage) }}" aria-label="末页">
                                        <span aria-hidden="true">&raquo;</span>
                                    </a>
                                </li>
                            @endif
                        </ul>
                    </nav>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>
@endsection 

@push('scripts')
<script>
console.log('Lottery scripts loaded');

document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded');
    
    const button = document.getElementById('startLotteryBtn');
    console.log('Found button:', button);
    
    if (button) {
        button.addEventListener('click', function() {
            console.log('Button clicked');
            startLottery();
        });
    }
});

function startLottery() {
    console.log('startLottery function called');
    
    // 禁用按钮，防止重复点击
    const button = document.getElementById('startLotteryBtn');
    console.log('Button element in startLottery:', button);
    
    if (!button) {
        console.error('Button not found!');
        return;
    }

    // 添加 CSRF token 检查
    const token = document.querySelector('meta[name="csrf-token"]');
    if (!token) {
        console.error('CSRF token not found!');
        return;
    }
    console.log('CSRF token found:', token.content);

    button.disabled = true;
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 摇奖中...';

    // 发送摇奖请求
    fetch('/admin/lottery/draw', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': token.content,
            'Accept': 'application/json'
        }
    })
    .then(response => {
        console.log('Response status:', response.status);
        return response.text().then(text => {
            console.log('Raw response:', text);
            try {
                return JSON.parse(text);
            } catch (e) {
                console.error('JSON parse error:', e);
                throw new Error('Invalid JSON response');
            }
        });
    })
    .then(data => {
        console.log('Parsed data:', data);
        if (data.success) {
            showWinner(data.data.winner);
        } else {
            alert(data.message || '摇奖失败，请重试');
        }
    })
    .catch(error => {
        console.error('Request error:', error);
        alert('摇奖过程中出现错误，请重试');
    })
    .finally(() => {
        button.disabled = false;
        button.innerHTML = '<i class="fas fa-gift"></i> 开始摇奖';
    });
}

function showWinner(winner) {
    // 显示中奖结果卡片
    const winnerCard = document.getElementById('winnerCard');
    winnerCard.style.display = 'block';

    // 更新中奖信息
    document.getElementById('winnerId').textContent = winner.id;
    document.getElementById('winnerNickname').textContent = winner.nickname || '未设置昵称';
    document.getElementById('winnerOpenid').textContent = winner.openid;
    document.getElementById('winnerCreatedAt').textContent = winner.created_at;

    // 滚动到中奖结果
    winnerCard.scrollIntoView({ behavior: 'smooth' });
}

function saveResult() {
    // 获取当前中奖用户ID
    const winnerId = document.getElementById('winnerId').textContent;
    
    if (!winnerId) {
        alert('未找到中奖用户信息');
        return;
    }

    // 禁用保存按钮
    const saveButton = document.getElementById('saveButton');
    saveButton.disabled = true;
    saveButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';

    // 发送保存请求
    fetch('/admin/lottery/save-result', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            'Accept': 'application/json'
        },
        body: JSON.stringify({
            winner_id: winnerId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('保存成功！');
            // 如果需要，重定向到中奖列表页面
            if (data.redirect) {
                window.location.href = data.redirect;
            }
        } else {
            alert(data.message || '保存结果失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('保存结果时出现错误');
    })
    .finally(() => {
        // 恢复保存按钮状态
        saveButton.disabled = false;
        saveButton.innerHTML = '<i class="fas fa-save"></i> 保存结果';
    });
}

// 保留原有的删除函数
function deleteLottery(id) {
    if (confirm('确定要删除这个摇奖活动吗？')) {
        axios.delete(`/admin/lottery/${id}`)
            .then(response => {
                if (response.data.success) {
                    location.reload();
                }
            })
            .catch(error => {
                alert('删除失败：' + error.response.data.message);
            });
    }
}
</script>
@endpush 